package org.mathcloud.math.core.generic.factory;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.mathcloud.math.core.common.factory.OperatorObjectFactory;
import org.mathcloud.math.core.common.operator.OperatorObject;
import org.mathcloud.math.core.common.signature.OperatorObjectSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.webequa.core.generic.factory.GenericOperatorObjectFactory;

public class GenericOperatorObjectFactory implements OperatorObjectFactory
{
	public GenericOperatorObjectFactory()
	{
		properties = null;
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	public OperatorObject newInstance(OperatorObjectSignature arg0)
	{		
		String impClassName = getImplementationClassName(arg0);
		if (impClassName!=null)
		{
			try
			{
				Class implementationClass = Class.forName(impClassName);
				try
				{
						return (OperatorObject)implementationClass.newInstance();
				} catch (InstantiationException e)
				{
						log.error("Cannot create instance - ",e);
						return null;
				} catch (IllegalAccessException e)
				{
					log.error("Cannot create instance - ",e);
					return null;
				}
			} catch (ClassNotFoundException e)
			{
				log.error("Cannot create instance - ",e);
				return null;
			}			
		} else return null;
	}
	
	public String getImplementationClassName(OperatorObjectSignature arg0)
	{
		if (properties!=null)
		{
			String key = arg0.getRealizationName()+"."+arg0.getMMLContentTag();
			return properties.getProperty(key); 
		}
		else return null;
	}
	
	public void setProperties(String fileName)
	{
		try
		{
			properties = new Properties();
			properties.load(new FileInputStream(fileName));						
		} catch (FileNotFoundException e)
		{
			log.error("Cannot set properties for factory - ",e);
		} catch (IOException e)
		{
			log.error("Cannot set properties for factory - ",e);
		}
	}
	
	public Properties getProperties()
	{
		return properties;
	}
	
	private Properties properties;
	
	private static final Logger log = LoggerFactory.getLogger(GenericOperatorObjectFactory.class);
}
